package com.example.publishDemo.Controller.imgUpload;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.StrUtil;
import com.example.publishDemo.Model.WangEditorVO;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;

@RestController
@RequestMapping("/files")
public class FileUploadController {
    private static final String PRODUCT_FILE_PREFIX = "D:\\IO\\illustration\\";
    private static final String SERVER_PREFIX = "http://localhost:8888/";

    //获取文章内图片
    @GetMapping("/{flag}")
    public void avatarPath(@PathVariable String flag, HttpServletResponse response) {
        if (!FileUtil.isDirectory(PRODUCT_FILE_PREFIX)) {
            FileUtil.mkdir(PRODUCT_FILE_PREFIX);
        }
        OutputStream os;
        List<String> fileNames = FileUtil.listFileNames(PRODUCT_FILE_PREFIX);
        String avatar = fileNames.stream().filter(name -> name.contains(flag)).findAny().orElse("");
        try{
            if (StrUtil.isNotEmpty(avatar)) {
                response.addHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(avatar,"UTF-8"));
                response.setContentType("application/octet-stream");
                byte[] bytes = FileUtil.readBytes(PRODUCT_FILE_PREFIX + avatar);
                os = response.getOutputStream();
                os.write(bytes);
                os.flush();
                os.close();
            }
        } catch (Exception e) {
            System.out.println("文件下载失败!");
        }
    }

    //errno,data是固定格式的键值对形式，不可更改
    @PostMapping("/wang/upload")
    public Map<String,Object> wangUpload(MultipartFile file) throws IOException {
        String flag = System.currentTimeMillis() + "";
        String filename = file.getOriginalFilename();
        try{
//            FileUtil.writeBytes(file.getBytes(), PRODUCT_FILE_PREFIX + flag + "-" + filename);
            FileUtil.writeBytes(file.getBytes(), PRODUCT_FILE_PREFIX + flag+getSuffix(file));
            System.out.println(filename+"---上传成功！");
            Thread.sleep(1L);
        } catch (Exception e) {
            System.err.println(filename+"---上传失败！");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("errno", 0);
        map.put("data", CollUtil.newArrayList(Dict.create().set("url", SERVER_PREFIX + "files/" + flag)));
        System.out.println(map.get("data"));
        return map;
    }

    // 获取文件的后缀名
    private String getSuffix(MultipartFile multipartFile) {
        String filename = multipartFile.getOriginalFilename();
        String fileSuffix = filename.substring(filename.lastIndexOf("."));
        return fileSuffix;
    }
}
